package com.xk.school_device.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.xk.school_device.common.Result;
import com.xk.school_device.entity.Assignments;
import com.xk.school_device.entity.Departments;
import com.xk.school_device.entity.Devices;
import com.xk.school_device.mapper.AssignmentsMapper;
import com.xk.school_device.mapper.DepartmentsMapper;
import com.xk.school_device.mapper.DevicesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xk
 * @since 2025-04-16
 */
@RestController
@RequestMapping("/api/departments")
public class DepartmentsController {

    @Autowired
    private DepartmentsMapper departmentMapper;

    @PostMapping("/getDepartments")
    public Result getDepartments(@RequestBody Departments departments) {
        return Result.success(departmentMapper.getDepartments(departments));
    }

    @Autowired
    private AssignmentsMapper assignmentsMapper;

    @Autowired
    private DevicesMapper devicesMapper;
    @PostMapping("create")
    public Result create(@RequestBody Assignments assignments) {
        Devices deviceById = devicesMapper.getDeviceById(assignments.getDeviceId());
        if (deviceById.getStatus().equals("in_use")) {
            return Result.failure("设备已被使用");
        }
        assignments.setAssignmentId(UUID.randomUUID().toString());
        String userId = StpUtil.getLoginIdAsString();
        assignments.setAssignedTo(userId);
        assignments.setStatus("assigned");
        devicesMapper.updateByIdStatus(assignments.getDeviceId(),"in_use");
        assignmentsMapper.insert(assignments);
        return Result.success("分配成功");
    }

}
